<?php

namespace app\http\controller;

use tmcore\services\pay\WechatPayService;

class WechatPay extends HttpController
{
    /**
     * 微信支付实例
     * @var WechatPayService
     */
    protected WechatPayService $payService;

    /**
     * 初始化
     */
    public function initialize()
    {
        $this->payService = new WechatPayService();
    }

    /**
     * 异步回调
     * @return \Psr\Http\Message\ResponseInterface|string
     */
    public function notify() {
        $notify = $this->payService->notify();
        if($notify) {
            if(isset($notify['event_type']) && $notify['event_type'] == 'TRANSACTION.SUCCESS') {
                $notify_data = $notify['resource']['ciphertext']; //回调参数
            }
            return $this->payService->notifySuccess();
        } else {
            return '验签失败';
        }
    }

    /**
     * 退款回调
     * @return \Psr\Http\Message\ResponseInterface|string
     */
    public function refund() {
        $notify = $this->payService->notify();
        if($notify) {
            if(isset($notify['event_type']) && $notify['event_type']) {
                $notify_data = $notify['resource']['ciphertext']; //回调参数
            }
            return $this->payService->notifySuccess();
        } else {
            return '验签失败';
        }
    }

    /**
     * 获取回调参数
     * @return mixed
     */
    private function getNotifyData() {
        return json_decode(file_get_contents('php://input'), true);
    }

    /**
     * 确认微信支付版本(v3|v2)
     * @return mixed
     */
    private function confirmVersion() {
        // 平台证书编号
        return isset($_SERVER['HTTP_WECHATPAY_SERIAL'])?'v3':'v2';
    }
}